import axios from 'axios'
import router from '@/router/index.js'
import {
	Message
} from "element-ui"

/**
 * axios默认配置
 */
var baseURL = "http://152.136.103.65:9909/api/Action/";
axios.defaults.withCredentials = true;
axios.defaults.timeout = 10000;
axios.defaults.baseURL = baseURL;

/**
 * 请求拦截器
 * @param {Object} config
 */
axios.interceptors.request.use(function(config) {
	if (sessionStorage.getItem('token')) {
		config.headers.Authorization = getToken();
	}
	return config;
}, function(error) {
	return Promise.reject(error);
});

/**
 * 响应拦截器
 * @param {Object} response
 */
axios.interceptors.response.use(function(response) {
	return response;
}, function(error) {
	if (error.response) {
		if (error.response.status === 404) {
			msgAlert('很抱歉，资源未找到!');
		}
		if (error.response.status === 401 || error.response.data.code === 401) {
			msgAlert('登陆已失效，请重新登陆!');
			setTimeout(() => {
				router.push('/login');
			}, 1000);
		}
	} else {
		msgAlert('请检查您的网络连接!');
	}
	return Promise.reject(error);
});

/** 
 * 错误提示
 * @param {Object} msg
 */
function msgAlert(msg) {
	Message.closeAll();
	if (msg) {
		Message.error('' + msg);
	}
}

/**
 * 接口调用成功结果处理
 * @param {Object} res
 * @param {Object} resolve
 */
function handleSuccess(res, resolve) {
	// 如果接口返回的code值为401,表示用户token过期，需要重新登陆
	if (res.status === 401 || res.data.code === 401) {
		// 提示
		msgAlert('登陆已失效，请重新登陆!');
		// 清空浏览器token
		sessionStorage.removeItem("token");
		// 跳转到登陆页
		setTimeout(() => {
			router.push('/login');
		}, 2000);
	} else if (res.status === 200 || res.data.code === 200) {
		// 结果正常处理
		resolve(res);
	} else {
		// 其他错误，弹窗提示
		msgAlert(res.data.msg);
	}
}

/**
 * 获取token
 */
function getToken() {
	return sessionStorage.token ? sessionStorage.token : "";
}

/**
 * 参数序列化
 * return 参数序列化结果
 */
function transformRequest(obj) {
	if (obj !== {} || obj !== null || obj !== '') {
		var str = [];
		for (var p in obj) {
			if (obj[p] instanceof Array) {
				obj[p].forEach(element => {
					str.push(encodeURIComponent(p) + "[]=" + encodeURIComponent(element));
				});
			} else {
				if (obj[p] !== undefined && obj[p] !== null) {
					//注：这里必须讲 false 排除在外，否则传入实际false将跳过处理。
					str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
				}
			}
		}
		return str.join("&");
	}
	return null;
}

/**
 * 修改响应数据
 * @param {Object} data
 */
function transformResponse(data) {
	// 对 data 进行任意转换处理
	return data;
}

/**
 * 异步请求方法
 */
var https = {
	get: function(url, params = {}) {
		return new Promise((resolve, reject) => {
			axios({
					method: "GET",
					url: url,
					params: params,
					headers: {
						token: getToken()
					}
				})
				.then(res => {
					handleSuccess(res, resolve);
				})
				.catch(err => {
					reject(err);
				});
		});
	},
	postJson: function(url, params = {}) {
		return new Promise((resolve, reject) => {
			axios({
					method: "POST",
					url: url,
					data: JSON.stringify(params),
					headers: {
						"Content-Type": "application/json",
						token: getToken()
					}
				})
				.then(res => {
					handleSuccess(res, resolve);
				})
				.catch(err => {
					reject(err);
				});
		});
	},
	// post方法,application/x-www-form-urlencoded序列化方式传递，参数形式未定
	postXform: function(url, params = {}) {
		return new Promise((resolve, reject) => {
			axios({
					method: "POST",
					url: url,
					data: transformRequest(params),
					headers: {
						"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
						token: getToken()
					}
				})
				.then(res => {
					handleSuccess(res, resolve);
				})
				.catch(err => {
					reject(err);
				});
		});
	},
	// 表单文件上传
	fileUpload: function(url, params = {}) {
		return new Promise((resolve, reject) => {
			axios({
					method: "POST",
					url: url,
					data: params,
					headers: {
						"Content-Type": "multipart/form-data",
						token: getToken()
					}
				})
				.then(res => {
					handleSuccess(res, resolve);
				})
				.catch(err => {
					reject(err);
				});
		});
	}
}

export default https;
